#include "popup.h"
#include <QtCore/QDebug>

Popup::Popup(QString message)
{
    running = false;
    m_message = message;
    //creating dialog
    dialog = new QDialog();
    dialog->setGeometry(0, 0, 200, 90);
    dialog->setWindowFlags(Qt::ToolTip);
    //setting background picture
    QPalette palette;
    palette.setBrush(QPalette::Window, QBrush(QPixmap(":/images/background.png")));
    dialog->setPalette(palette);
    dialog->setAutoFillBackground(true);
    //creating label
    label = new QLabel(dialog);
    label->setGeometry(10, 10, 181, 51);
    label->setAlignment(Qt::AlignTop);
    label->setWordWrap(true);
    label->setText("<font color=white>"+m_message+"</font>");
}

Popup::~Popup()
{
    running = false;
    delete label;
    dialog->hide();
    delete dialog;
}

void Popup::msleep(int msecs)
{
    QTime dieTime = QTime::currentTime().addMSecs(msecs);
    while( QTime::currentTime() < dieTime)
            QCoreApplication::processEvents(QEventLoop::AllEvents, msecs);
}

void Popup::run()
{
    //running
    running = true;
    int availableWidth = QApplication::desktop()->availableGeometry().width();
    int availableHeight = QApplication::desktop()->availableGeometry().height();
    int availableLeft = QApplication::desktop()->availableGeometry().left();
    int availableTop = QApplication::desktop()->availableGeometry().top();
    int fullHeight = QApplication::desktop()->screenGeometry().height();
    int scrollSpeed = 3;
    int scrollSleep = 5;
    qDebug("Showing popup");
    dialog->show();
    for (int top = fullHeight; (top > availableTop + availableHeight - dialog->height() - 1  && running); top-=scrollSpeed, scrollSleep += (fullHeight - top) / 80)
    {
        dialog->move(availableLeft + availableWidth - dialog->width(), top);
        msleep(scrollSleep);
    }
    qDebug("Waiting");
    if (running)
        msleep(3000);
    qDebug("Hiding popup");
    for (int top = availableTop + availableHeight - dialog->height(); (top <= fullHeight && running); top+=scrollSpeed, scrollSleep -= (fullHeight - top) / 80)
    {
        dialog->move(availableLeft + availableWidth - dialog->width(), top);
        msleep(scrollSleep);
    }
    dialog->hide();
    running = false;
}
